import Router from 'vue-router';
import Vue from 'vue';
import store from '@/store'
// import store from '../store'; // 引入 Vuex store
Vue.use(Router);


const routes = [
  {
    path: '/',
    name: 'HomePage',
    component: () => import('../views/HomePage.vue'),
    children: [
      {
        path: '/company',
        name: 'Company',
        component: () => import('../views/company/CompanyPage.vue'),
      },
      {
        path: '/farmer',
        name: 'Farmer',
        component: () => import('../views/farmer/FarmerPage.vue'),
      },
      {
        path: '/map',
        name: 'Map',
        component: () => import('../views/common/MapPage.vue'),
      },
      {
        path: '/sc',
        name: 'sc',
        component: () => import('../views/common/MarketPage.vue'),
      },
      {
        path: '/index',
        name: 'Index',
        component: () => import('../views/common/IndexPage.vue'),
      },
      {
        path: '/demand',
        name: 'Demand',
        component: () => import('../views/company/DemandPage.vue'),
      },
      {
        path: '/product',
        name: 'Demand',
        component: () => import('../views/farmer/ProductPage.vue'),
      },
      {
        path: '/front/:id',
        name: 'front',
        component: () => import('../views/company/FrontPage.vue'),
      },
      {
        path: '/farmerFront/:id',
        name: 'farmerFront',
        component: () => import('../views/farmer/FrontPage.vue'),
      },
    ],
  },
  {
    path: '/login',
    component: () => import('@/views/LoginPage.vue'),
  },
  {
    path: '/register',
    component: () => import('@/views/RegisterPage.vue'),
  },
  {
    path: '/admin',
    component: () => import('@/views/AdminPage.vue'),
    meta: {
      requiresAuth: true,
      roles: ['admin'],
    }
  },
  {
    path: '/user',
    component: () => import('@/views/UserPage.vue'),
    meta: {
      requiresAuth: true,
      roles: ['user'],
    }
  }
];

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});


// 获取用户角色函数
function getUserRole() {
  const role = store.getters.user ? store.getters.user.role : null;
  return role;
}


router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
      const userRole = getUserRole();
      if (!userRole) {
          next({ path: '/login' });
      } else if (to.meta.roles && to.meta.roles.indexOf(userRole) === -1) {
          next({ path: '/unauthorized' });
      } else {
          next();
      }
  } else {
      next();
  }
});


// 导航栏中用到了路由 防止重复点同一个菜单给出错误提示
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};

export default router;
